#include <jni.h>
#include <string>

#include <android/log.h>

#define LOG_TAG "android-ffmpeg-cmake"
#define LOGI(...) __android_log_print(4, LOG_TAG, __VA_ARGS__);
#define LOGE(...) __android_log_print(6, LOG_TAG, __VA_ARGS__);


extern "C"
{

#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>

char* jstringTostring(JNIEnv* env, jstring jstr)
    {
        char* rtn = NULL;
        jclass clsstring = env->FindClass("java/lang/String");
        jstring strencode = env->NewStringUTF("utf-8");
        jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
        jbyteArray barr= (jbyteArray)env->CallObjectMethod(jstr, mid, strencode);
        jsize alen = env->GetArrayLength(barr);
        jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);
        if (alen > 0)
        {
            rtn = (char*)malloc(alen + 1);
            memcpy(rtn, ba, alen);
            rtn[alen] = 0;
        }
        env->ReleaseByteArrayElements(barr, ba, 0);
        return rtn;
    }

    JNIEXPORT jstring JNICALL
    Java_care_www_ffmpeg_utils_FFmpegUtils_stringFromJNI(
            JNIEnv *env,
            jobject /* this */) {
        std::string hello = "FFmpegUtils:Hello from C++";
        return env->NewStringUTF(hello.c_str());
    }

    JNIEXPORT jstring JNICALL
    Java_care_www_ffmpeg_utils_FFmpegUtils_videoInfo(
                                                        JNIEnv *env,
                                                        jobject /* this */obj,
                                                        jstring  jFilePath
                                                    ) {
        /**
         * avcodec_configuration:
         * --prefix=/Users/zhupei/Downloads/ffmpeg-3.3/android/arm --disable-shared
         * --enable-static --disable-doc --disable-programs --enable-small -
         * -disable-avdevice --disable-devices --disable-protocols
         * --enable-protocol=file --enable-cross-compile
         * --cross-prefix=/Users/zhupei/Documents/adt-bundle-mac-x86_64-20140702/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/bin/arm-linux-androideabi-
         * --sysroot=/Users/zhupei/Documents/adt-bundle-mac-x86_64-20140702/sdk/ndk-bundle/platforms/android-14/arch-arm
         * --extra-cflags='-Os -fpic'
         * --extra-ldflags= --arch=arm --target-os=android
         */

        LOGE("avcodec_configuration : %s",avcodec_configuration());
        // Java string -> c char* (JNI)
        const char* filePath = env->GetStringUTFChars(jFilePath,JNI_FALSE);
        LOGE("FilePath : %s",filePath);
        int angle = -1;
//1.注册所有组件
        av_register_all();
//封装格式上下文
        AVFormatContext *pFormatCtx = avformat_alloc_context();

        int err_code = avformat_open_input(&pFormatCtx, filePath, NULL, NULL);

        LOGE("read code %d",err_code);

        if( err_code != 0)
        {
            return NULL;
        }

        //2.打开输入视频文件
        if(avformat_open_input(&pFormatCtx, filePath, NULL,NULL) != 0){
            LOGE("%s","无法打开输入视频文件");
            return NULL;
        }
        //3.获取视频文件信息
        if(avformat_find_stream_info(pFormatCtx, NULL) < 0){
            LOGE("%s","无法获取视频信息");
            return NULL;
        }
        //获取视频流的索引位置
        int v_stream_idx = -1;
        int i = 0;
        for(i = 0; i < pFormatCtx->nb_streams; i++){
            if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO){
                v_stream_idx = i;
                break;
            }
        }
        //获取视频方向数据
        AVDictionaryEntry *tag = NULL;
        tag = av_dict_get(pFormatCtx->streams[v_stream_idx]->metadata, "rotate", tag, 0);
        if(tag != NULL){
            angle = atoi(tag->value);
            LOGE("angle %d", angle);
        }


        //分辨率
        LOGE("width:%d", pFormatCtx->streams[v_stream_idx]->codecpar->width);
        LOGE("height:%d", pFormatCtx->streams[v_stream_idx]->codecpar->height);
        LOGE("duration:%d", pFormatCtx->streams[v_stream_idx]->duration);
        LOGE("nb_framges:%d", pFormatCtx->streams[v_stream_idx]->nb_frames);
        LOGE("time_base.num:%d", pFormatCtx->streams[v_stream_idx]->time_base.num);

        // Close the video file
        avformat_close_input(&pFormatCtx);

        std::string hello = "Get Video Info Success!";
        return env->NewStringUTF(hello.c_str());
    }


}
